/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package parsers;

import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author joen
 */
public class XmlParsing {
    private static final Logger logger = LoggerFactory.getLogger(XmlParsing.class);
    private static Document xDoc;
    
    public XmlParsing(String xmlFile) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        xDoc = builder.parse(new FileInputStream(new File(xmlFile)));
    }
    
    public int getChildCount(String parentTag, int parentIndex, String childTag) {
        NodeList list = xDoc.getElementsByTagName(parentTag);
        Element parent = (Element) list.item(parentIndex);
        NodeList  childList = parent.getElementsByTagName(childTag);
        return childList.getLength();
    }
    
    public String getChildValue(String parentTag, int parentIndex, String childTag, int childIndex) {
        NodeList list = xDoc.getElementsByTagName(parentTag);
        Element parent = (Element) list.item(parentIndex);
        NodeList childList = parent.getElementsByTagName(childTag);
        Element field = (Element) childList.item(childIndex);
        Node child = field.getFirstChild();
        if (child instanceof CharacterData) {
            CharacterData cd = (CharacterData) child;
            return cd.getData();
        }
        return "";
    }
    
    public String getAttributeValue(String elemetTag, int elementIndex, String attributeTag) {
        NodeList list = xDoc.getElementsByTagName(elemetTag);
        Element element = (Element) list.item(elementIndex);
        return element.getAttribute(attributeTag);
    }
    
}
